package com.keyancompany.zhongbaopingtai.weight;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.EditText;

import com.keyancompany.zhongbaopingtai.R;
import com.keyancompany.zhongbaopingtai.listener.IEditTextEmptyListener;


public class CustomEditText extends EditText {
    private Context mContext;
    private int mDrawableWidth;
    private IEditTextEmptyListener emptyListener;
    private Drawable imgLeftInable;
    private Drawable imgRightInable;
    private boolean isClickRight = true;

    public void setEmptyListener(IEditTextEmptyListener emptyListener) {
        this.emptyListener = emptyListener;
    }

    public CustomEditText(Context context) {
        super(context);
        mContext = context;
        init();

    }

    /**
     * 右边的图标是否可以点击
     *
     * @param isClickable
     */
    public void setIsClickRightIcon(boolean isClickable) {
        this.isClickRight = isClickable;
    }

    public CustomEditText(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        mContext = context;
        TypedArray a = context.obtainStyledAttributes(attrs,
                R.styleable.custom_edittext);
        imgLeftInable = mContext.getResources().getDrawable(
                a.getResourceId(R.styleable.custom_edittext_leftIcon, 0));
        int leftId = a.getResourceId(R.styleable.custom_edittext_leftIcon, 0);
        if (leftId != 0) {
            imgLeftInable = mContext.getResources().getDrawable(leftId);
        }
        int rightId = a.getResourceId(R.styleable.custom_edittext_rightIcon, 0);
        if (rightId != 0) {
            imgRightInable = mContext.getResources().getDrawable(rightId);
        }
        if (imgLeftInable != null) {
            mDrawableWidth = imgLeftInable.getIntrinsicWidth() - 5;
            setCompoundDrawablesWithIntrinsicBounds(imgLeftInable, null, null, null);
            setCompoundDrawablePadding(mDrawableWidth);
        }
        if (imgRightInable != null) {
            mDrawableWidth = imgRightInable.getIntrinsicWidth() - 5;
            setCompoundDrawablesWithIntrinsicBounds(null, null,
                    imgRightInable, null);
            setCompoundDrawablePadding(mDrawableWidth);
        }
        a.recycle();
        init();
    }

    public CustomEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
        TypedArray a = context.obtainStyledAttributes(attrs,
                R.styleable.custom_edittext);
        int leftId = a.getResourceId(R.styleable.custom_edittext_leftIcon, 0);
        if (leftId != 0) {
            imgLeftInable = mContext.getResources().getDrawable(leftId);
        }
        int rightId = a.getResourceId(R.styleable.custom_edittext_rightIcon, 0);
        if (rightId != 0) {
            imgRightInable = mContext.getResources().getDrawable(rightId);
        }
//        if (imgLeftInable != null) {
//            mDrawableWidth = imgLeftInable.getIntrinsicWidth() - 5;

//        }
//        if (imgRightInable != null) {
//            mDrawableWidth = imgRightInable.getIntrinsicWidth() - 5;
//            setCompoundDrawablesWithIntrinsicBounds(null, null,
//                    imgRightInable, null);
//            setCompoundDrawablePadding(mDrawableWidth);
//        }
        setDrawable();
        init();
    }

    private void init() {
        // imgRightInable =
        // mContext.getResources().getDrawable(R.drawable.back);
        // mDrawableWidth = imgRightInable.getIntrinsicWidth() + 10;
        addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                setDrawable();
                String temp = "";
                if (!TextUtils.isEmpty(s.toString()))
                    temp = s.toString();
                if (emptyListener != null)
                    emptyListener.contentEmpty(temp.length());
            }
        });
        setDrawable();
    }

    private void setDrawable() {
        if (length() > 0) {
            setCompoundDrawablesWithIntrinsicBounds(imgLeftInable != null ? imgLeftInable : null, null,
                    imgRightInable != null ? imgRightInable : null, null);
            setCompoundDrawablePadding(mDrawableWidth);
        } else {
            setCompoundDrawablesWithIntrinsicBounds(imgLeftInable != null ? imgLeftInable : null, null, null,
                    null);
        }
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (imgRightInable != null
                && event.getAction() == MotionEvent.ACTION_UP && isClickRight) {
            int x = (int) event.getX();
            // 判断触摸点是否在水平范围内
            boolean isInnerWidth = (x > (getWidth() - getTotalPaddingRight()))
                    && (x < (getWidth() - getPaddingRight()));
            // 获取删除图标的边界，返回一个Rect对象
            Rect rect = imgRightInable.getBounds();
            // 获取删除图标的高度
            int height = rect.height();
            int y = (int) event.getY();
            // 计算图标底部到控件底部的距离
            int distance = (getHeight() - height) / 2;
            // 判断触摸点是否在竖直范围内(可能会有点误差)
            // 触摸点的纵坐标在distance到（distance+图标自身的高度）之内，则视为点中删除图标
            boolean isInnerHeight = (y > distance) && (y < (distance + height));

            if (isInnerWidth && isInnerHeight) {
                setText("");
                if (emptyListener != null)
                    emptyListener.contentEmpty(0);
            }

        }
        return super.onTouchEvent(event);
    }

    @Override
    protected void onFocusChanged(boolean focused, int direction,
                                  Rect previouslyFocusedRect) {
        // TODO Auto-generated method stub
        if (focused) {
            setDrawable();
        } else {
            setCompoundDrawablesWithIntrinsicBounds(null, null, null,
                    null);
        }
        super.onFocusChanged(focused, direction, previouslyFocusedRect);
    }

}